package com.cinema.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cinema.Bean.Movie;
import com.cinema.dao.IMovieDao;
import com.cinema.dao.imp.MovieDaoMysql;

public class MovieServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	private IMovieDao iMovieDao = new MovieDaoMysql();
	
	public void picUpload(HttpServletRequest request) {
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		String method = request.getParameter("method");
		// 影片新增
		if ("add".equals(method)) {
			// 1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录  
			DiskFileItemFactory factory=new DiskFileItemFactory();
			// 2. 创建ServletFileUpload对象
			ServletFileUpload upload=new ServletFileUpload(factory);
		
			String uploadDirPath=request.getRealPath("/upload");
			File uploadDir=new File(uploadDirPath);
			if(!uploadDir.exists()||!uploadDir.isDirectory()){
				uploadDir.mkdir();
			}
			 // 判断enctype属性是否为multipart/form-data    
			if(ServletFileUpload.isMultipartContent(request)){ // true
				try {
					List<FileItem> fiList=upload.parseRequest(request);
					if(fiList!=null){
						List<Map<String,String>> resultList=new ArrayList<Map<String,String>>();
						for(int i=0;i<fiList.size();i++){
							
							FileItem currFi=fiList.get(i);
							Map<String,String> currRel=new HashMap<String,String>();
							
							// 普通表单元素
							if(currFi.isFormField()){
								currRel.put("name", currFi.getFieldName()); // name属性值
								currRel.put("value", currFi.getString("utf-8")); // name属性对应的value值
								
							}else{// <input type="file">的上传文件的元素  
								
								// 文件名称
								String fileName=currFi.getName();
								
								// 扩展名
								int poiIndex=fileName.lastIndexOf(".");
								String suffixName=fileName.substring(poiIndex);
								
								// 获取当前时间
								Date now=new Date();
								SimpleDateFormat dFormat=new SimpleDateFormat("yyyyMMddHHmmssSSS");
								
								// 新命名(唯一)
								String newFileName=dFormat.format(now)+suffixName;
								
								// 写入文件
								FileOutputStream fos= new FileOutputStream(uploadDirPath+"/"+newFileName);
								InputStream is=currFi.getInputStream();
								byte b[]=new byte[1024];
								int len=0;
								while((len=is.read(b))>0){
									fos.write(b, 0, len);
								}
								currRel.put("name", currFi.getFieldName());
								currRel.put("value", newFileName);
							}
							resultList.add(currRel);
						}
						
						Movie m = new Movie();
						String durationStr = null;
						String movieStatStr = null;
						for(int i = 0;i<resultList.size();i++) {
							Map<String,String> currRel1 = resultList.get(i);
							String value = currRel1.get("name"); 
							if(value.equals("poster")) {
								m.setPoster(currRel1.get("value")); 
							}
							if(value.equals("manActorPic")) {
								m.setManActorPic(currRel1.get("value")); 
							}
							if(value.equals("womanActorPic")) {
								m.setWomanActorPic(currRel1.get("value")); 
							}
							if(value.equals("movieId")) {
								m.setMovieId(currRel1.get("value")); 
							}
							if(value.equals("movieName")) {
								m.setMovieName(currRel1.get("value")); 
							}
							if(value.equals("starring")) {
								m.setStarring(currRel1.get("value")); 
							}
							if(value.equals("detail")) {
								m.setDetail(currRel1.get("value")); 
							}
							if(value.equals("duration")) {
								durationStr = currRel1.get("value");
								Integer duration = Integer.parseInt(durationStr);
								m.setDuration(duration); 
							}
							if(value.equals("director")) {
								m.setDirector(currRel1.get("value")); 
							}
							if(value.equals("language")) {
								m.setLanguage(currRel1.get("value")); 
							}
							if(value.equals("movieType")) {
								m.setMovieType(currRel1.get("value")); 
							}
							if(value.equals("slogan")) {
								m.setSlogan(currRel1.get("value")); 
							}
							if(value.equals("releaseTime")) {
								m.setReleaseTime(currRel1.get("value")); 
							}
							if(value.equals("movieStat")) {
								movieStatStr = currRel1.get("value");
								Integer movieStat = Integer.parseInt(movieStatStr);
								m.setMovieStat(movieStat); 
							}
						}
						
						int insert = iMovieDao.insert(m);
						
						if (insert == 1) {
							
							request.getSession().removeAttribute("mlist");
						}
						
						response.sendRedirect("Movie/index.jsp");
						
					}
				} catch (FileUploadException e) {
					
					e.printStackTrace();
				}
			}

		} else if ("delete".equals(method)) {
			String movieId = request.getParameter("movieId");
			if (movieId != null && movieId != "") {

				Movie movie = new Movie();
				movie.setMovieId(movieId);

				int delete = iMovieDao.delete(movie);

				if (delete == 1) {
					response.getWriter().print("success");
					request.getSession().removeAttribute("mlist");
				} else {
					response.getWriter().print("error");
				}
			}
		} else if ("getMovie".equals(method)) {
			String movieId = request.getParameter("movieId");

			if (movieId != null && movieId != "") {
				Movie movie = iMovieDao.SelectById(movieId);
				
				request.setAttribute("movie", movie);
			}
			request.getRequestDispatcher("/Movie/edit.jsp").forward(request, response);

		} else if ("update".equals(method)) {
			// 1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录  
			DiskFileItemFactory factory=new DiskFileItemFactory();
			// 2. 创建ServletFileUpload对象
			ServletFileUpload upload=new ServletFileUpload(factory);
		
			String uploadDirPath=request.getRealPath("/upload");
			File uploadDir=new File(uploadDirPath);
			if(!uploadDir.exists()||!uploadDir.isDirectory()){
				uploadDir.mkdir();
			}
			 // 判断enctype属性是否为multipart/form-data    
			if(ServletFileUpload.isMultipartContent(request)){ // true
				try {
					List<FileItem> fiList=upload.parseRequest(request);
					if(fiList!=null){
						List<Map<String,String>> resultList=new ArrayList<Map<String,String>>();
						for(int i=0;i<fiList.size();i++){
							
							FileItem currFi=fiList.get(i);
							Map<String,String> currRel=new HashMap<String,String>();
							
							// 普通表单元素
							if(currFi.isFormField()){ 
								
								currRel.put("name", currFi.getFieldName()); // name属性值
								currRel.put("value", currFi.getString("utf-8")); // name属性对应的value值
								
							}else{// <input type="file">的上传文件的元素  
								
								// 文件名称
								String fileName=currFi.getName();
								
								// 扩展名
								int poiIndex=fileName.lastIndexOf(".");
								String suffixName=fileName.substring(poiIndex);
								
								// 获取当前时间
								Date now=new Date();
								SimpleDateFormat dFormat=new SimpleDateFormat("yyyyMMddHHmmssSSS");
								
								// 新命名(唯一)
								String newFileName=dFormat.format(now)+suffixName;
								
								// 写入文件
								FileOutputStream fos= new FileOutputStream(uploadDirPath+"/"+newFileName);
								InputStream is=currFi.getInputStream();
								byte b[]=new byte[1024];
								int len=0;
								while((len=is.read(b))>0){
									fos.write(b, 0, len);
								}
								currRel.put("name", currFi.getFieldName());
								currRel.put("value", newFileName);
							}
							resultList.add(currRel);
						}
						String movieId = null;
						String movieName = null;
						String starring = null;
						String detail = null;
						String durationStr = null;
						Integer duration = null;
						String director = null;
						String language = null;
						String movieType = null;
						String slogan = null;
						String poster = null;
						String manActorPic = null;
						String womanActorPic = null;
						String releaseTime = null;
						String movieStatStr = null;
						Integer movieStat=null;
						
						for(int i = 0;i<resultList.size();i++) {
							Map<String,String> currRel1 = resultList.get(i);
							String value = currRel1.get("name"); 
							if(value.equals("poster")) {
								poster = currRel1.get("value");
							}
							if(value.equals("manActorPic")) {
								manActorPic = currRel1.get("value");
							}
							if(value.equals("womanActorPic")) {
								womanActorPic = currRel1.get("value");
							}
							if(value.equals("movieId")) {
								movieId = currRel1.get("value");
							}
							if(value.equals("movieName")) {
								movieName = currRel1.get("value"); 
							}
							if(value.equals("starring")) {
								starring = currRel1.get("value"); 
							}
							if(value.equals("detail")) {
								detail = currRel1.get("value");
							}
							if(value.equals("duration")) {
								durationStr = currRel1.get("value");
								duration = Integer.parseInt(durationStr);
							}
							if(value.equals("director")) {
								director = currRel1.get("value");
							}
							if(value.equals("language")) {
								language = currRel1.get("value");
							}
							if(value.equals("movieType")) {
								movieType = currRel1.get("value");
							}
							if(value.equals("slogan")) {
								slogan = currRel1.get("value");
							}
							if(value.equals("releaseTime")) {
								releaseTime = currRel1.get("value");
							}
							if(value.equals("movieStat")) {
								movieStatStr = currRel1.get("value");
								movieStat = Integer.parseInt(movieStatStr);
							}
						}
						
						Movie movie = new Movie(movieId, movieName, starring, detail, duration, director, language, movieType,
								slogan, poster, manActorPic, womanActorPic, releaseTime, movieStat);
						
						int update = iMovieDao.update(movie);
						
						if (update == 1) {
							request.getSession().removeAttribute("mlist");
						}
						response.sendRedirect("Movie/index.jsp");
					}
				} catch (FileUploadException e) {
					
					e.printStackTrace();
				}
			}

		} else if ("select".equals(method)) {
			request.getSession().removeAttribute("mlist");
			String keyword = request.getParameter("keyword");

			List<Movie> movies = iMovieDao.Select(keyword);
			request.getSession().setAttribute("mlist", movies);
		}
	}
}
